<!doctype html>

<html>
<head>
  <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
  <title>nativemessagingtransport.js (Closure Library API Documentation - JavaScript)</title>
  <link rel="stylesheet" href="static/css/base.css">
  <link rel="stylesheet" href="static/css/doc.css">
  <link rel="stylesheet" href="static/css/sidetree.css">
  <link rel="stylesheet" href="static/css/prettify.css">

  <script>
     var _staticFilePath = "static/";
     var _typeTreeName = "goog";
     var _fileTreeName = "Source";
  </script>

  <script src="static/js/doc.js">
  </script>


  <meta charset="utf8">
</head>

<body onload="grokdoc.onLoad();">

<div id="header">
  <div class="g-section g-tpl-50-50 g-split">
    <div class="g-unit g-first">
      <a id="logo" href="index.html">Closure Library API Documentation</a>
    </div>

    <div class="g-unit">
      <div class="g-c">
        <strong>Go to class or file:</strong>
        <input type="text" id="ac">
      </div>
    </div>
  </div>
</div>

<div class="clear"></div>

<h2><a href="local_closure_goog_net_xpc_nativemessagingtransport.js.html">nativemessagingtransport.js</a></h2>

<pre class="prettyprint lang-js">
<a name="line1"></a>// Copyright 2007 The Closure Library Authors. All Rights Reserved.
<a name="line2"></a>//
<a name="line3"></a>// Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
<a name="line4"></a>// you may not use this file except in compliance with the License.
<a name="line5"></a>// You may obtain a copy of the License at
<a name="line6"></a>//
<a name="line7"></a>//      http://www.apache.org/licenses/LICENSE-2.0
<a name="line8"></a>//
<a name="line9"></a>// Unless required by applicable law or agreed to in writing, software
<a name="line10"></a>// distributed under the License is distributed on an &quot;AS-IS&quot; BASIS,
<a name="line11"></a>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<a name="line12"></a>// See the License for the specific language governing permissions and
<a name="line13"></a>// limitations under the License.
<a name="line14"></a>
<a name="line15"></a>/**
<a name="line16"></a> * @fileoverview Contains the class which uses native messaging
<a name="line17"></a> * facilities for cross domain communication.
<a name="line18"></a> *
<a name="line19"></a> */
<a name="line20"></a>
<a name="line21"></a>
<a name="line22"></a>goog.provide(&#39;goog.net.xpc.NativeMessagingTransport&#39;);
<a name="line23"></a>
<a name="line24"></a>goog.require(&#39;goog.Timer&#39;);
<a name="line25"></a>goog.require(&#39;goog.asserts&#39;);
<a name="line26"></a>goog.require(&#39;goog.async.Deferred&#39;);
<a name="line27"></a>goog.require(&#39;goog.events&#39;);
<a name="line28"></a>goog.require(&#39;goog.events.EventHandler&#39;);
<a name="line29"></a>goog.require(&#39;goog.log&#39;);
<a name="line30"></a>goog.require(&#39;goog.net.xpc&#39;);
<a name="line31"></a>goog.require(&#39;goog.net.xpc.CrossPageChannelRole&#39;);
<a name="line32"></a>goog.require(&#39;goog.net.xpc.Transport&#39;);
<a name="line33"></a>goog.require(&#39;goog.net.xpc.TransportTypes&#39;);
<a name="line34"></a>
<a name="line35"></a>
<a name="line36"></a>
<a name="line37"></a>/**
<a name="line38"></a> * The native messaging transport
<a name="line39"></a> *
<a name="line40"></a> * Uses document.postMessage() to send messages to other documents.
<a name="line41"></a> * Receiving is done by listening on &#39;message&#39;-events on the document.
<a name="line42"></a> *
<a name="line43"></a> * @param {goog.net.xpc.CrossPageChannel} channel The channel this
<a name="line44"></a> *     transport belongs to.
<a name="line45"></a> * @param {string} peerHostname The hostname (protocol, domain, and port) of the
<a name="line46"></a> *     peer.
<a name="line47"></a> * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for
<a name="line48"></a> *     finding the correct window/document.
<a name="line49"></a> * @param {boolean=} opt_oneSidedHandshake If this is true, only the outer
<a name="line50"></a> *     transport sends a SETUP message and expects a SETUP_ACK.  The inner
<a name="line51"></a> *     transport goes connected when it receives the SETUP.
<a name="line52"></a> * @param {number=} opt_protocolVersion Which version of its setup protocol the
<a name="line53"></a> *     transport should use.  The default is &#39;2&#39;.
<a name="line54"></a> * @constructor
<a name="line55"></a> * @extends {goog.net.xpc.Transport}
<a name="line56"></a> * @final
<a name="line57"></a> */
<a name="line58"></a>goog.net.xpc.NativeMessagingTransport = function(channel, peerHostname,
<a name="line59"></a>    opt_domHelper, opt_oneSidedHandshake, opt_protocolVersion) {
<a name="line60"></a>  goog.net.xpc.NativeMessagingTransport.base(
<a name="line61"></a>      this, &#39;constructor&#39;, opt_domHelper);
<a name="line62"></a>
<a name="line63"></a>  /**
<a name="line64"></a>   * The channel this transport belongs to.
<a name="line65"></a>   * @type {goog.net.xpc.CrossPageChannel}
<a name="line66"></a>   * @private
<a name="line67"></a>   */
<a name="line68"></a>  this.channel_ = channel;
<a name="line69"></a>
<a name="line70"></a>  /**
<a name="line71"></a>   * Which version of the transport&#39;s protocol should be used.
<a name="line72"></a>   * @type {number}
<a name="line73"></a>   * @private
<a name="line74"></a>   */
<a name="line75"></a>  this.protocolVersion_ = opt_protocolVersion || 2;
<a name="line76"></a>  goog.asserts.assert(this.protocolVersion_ &gt;= 1);
<a name="line77"></a>  goog.asserts.assert(this.protocolVersion_ &lt;= 2);
<a name="line78"></a>
<a name="line79"></a>  /**
<a name="line80"></a>   * The hostname of the peer. This parameterizes all calls to postMessage, and
<a name="line81"></a>   * should contain the precise protocol, domain, and port of the peer window.
<a name="line82"></a>   * @type {string}
<a name="line83"></a>   * @private
<a name="line84"></a>   */
<a name="line85"></a>  this.peerHostname_ = peerHostname || &#39;*&#39;;
<a name="line86"></a>
<a name="line87"></a>  /**
<a name="line88"></a>   * The event handler.
<a name="line89"></a>   * @type {!goog.events.EventHandler.&lt;!goog.net.xpc.NativeMessagingTransport&gt;}
<a name="line90"></a>   * @private
<a name="line91"></a>   */
<a name="line92"></a>  this.eventHandler_ = new goog.events.EventHandler(this);
<a name="line93"></a>
<a name="line94"></a>  /**
<a name="line95"></a>   * Timer for connection reattempts.
<a name="line96"></a>   * @type {!goog.Timer}
<a name="line97"></a>   * @private
<a name="line98"></a>   */
<a name="line99"></a>  this.maybeAttemptToConnectTimer_ = new goog.Timer(100, this.getWindow());
<a name="line100"></a>
<a name="line101"></a>  /**
<a name="line102"></a>   * Whether one-sided handshakes are enabled.
<a name="line103"></a>   * @type {boolean}
<a name="line104"></a>   * @private
<a name="line105"></a>   */
<a name="line106"></a>  this.oneSidedHandshake_ = !!opt_oneSidedHandshake;
<a name="line107"></a>
<a name="line108"></a>  /**
<a name="line109"></a>   * Fires once we&#39;ve received our SETUP_ACK message.
<a name="line110"></a>   * @type {!goog.async.Deferred}
<a name="line111"></a>   * @private
<a name="line112"></a>   */
<a name="line113"></a>  this.setupAckReceived_ = new goog.async.Deferred();
<a name="line114"></a>
<a name="line115"></a>  /**
<a name="line116"></a>   * Fires once we&#39;ve sent our SETUP_ACK message.
<a name="line117"></a>   * @type {!goog.async.Deferred}
<a name="line118"></a>   * @private
<a name="line119"></a>   */
<a name="line120"></a>  this.setupAckSent_ = new goog.async.Deferred();
<a name="line121"></a>
<a name="line122"></a>  /**
<a name="line123"></a>   * Fires once we&#39;re marked connected.
<a name="line124"></a>   * @type {!goog.async.Deferred}
<a name="line125"></a>   * @private
<a name="line126"></a>   */
<a name="line127"></a>  this.connected_ = new goog.async.Deferred();
<a name="line128"></a>
<a name="line129"></a>  /**
<a name="line130"></a>   * The unique ID of this side of the connection. Used to determine when a peer
<a name="line131"></a>   * is reloaded.
<a name="line132"></a>   * @type {string}
<a name="line133"></a>   * @private
<a name="line134"></a>   */
<a name="line135"></a>  this.endpointId_ = goog.net.xpc.getRandomString(10);
<a name="line136"></a>
<a name="line137"></a>  /**
<a name="line138"></a>   * The unique ID of the peer. If we get a message from a peer with an ID we
<a name="line139"></a>   * don&#39;t expect, we reset the connection.
<a name="line140"></a>   * @type {?string}
<a name="line141"></a>   * @private
<a name="line142"></a>   */
<a name="line143"></a>  this.peerEndpointId_ = null;
<a name="line144"></a>
<a name="line145"></a>  // We don&#39;t want to mark ourselves connected until we have sent whatever
<a name="line146"></a>  // message will cause our counterpart in the other frame to also declare
<a name="line147"></a>  // itself connected, if there is such a message.  Otherwise we risk a user
<a name="line148"></a>  // message being sent in advance of that message, and it being discarded.
<a name="line149"></a>  if (this.oneSidedHandshake_) {
<a name="line150"></a>    if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.INNER) {
<a name="line151"></a>      // One sided handshake, inner frame:
<a name="line152"></a>      // SETUP_ACK must be received.
<a name="line153"></a>      this.connected_.awaitDeferred(this.setupAckReceived_);
<a name="line154"></a>    } else {
<a name="line155"></a>      // One sided handshake, outer frame:
<a name="line156"></a>      // SETUP_ACK must be sent.
<a name="line157"></a>      this.connected_.awaitDeferred(this.setupAckSent_);
<a name="line158"></a>    }
<a name="line159"></a>  } else {
<a name="line160"></a>    // Two sided handshake:
<a name="line161"></a>    // SETUP_ACK has to have been received, and sent.
<a name="line162"></a>    this.connected_.awaitDeferred(this.setupAckReceived_);
<a name="line163"></a>    if (this.protocolVersion_ == 2) {
<a name="line164"></a>      this.connected_.awaitDeferred(this.setupAckSent_);
<a name="line165"></a>    }
<a name="line166"></a>  }
<a name="line167"></a>  this.connected_.addCallback(this.notifyConnected_, this);
<a name="line168"></a>  this.connected_.callback(true);
<a name="line169"></a>
<a name="line170"></a>  this.eventHandler_.
<a name="line171"></a>      listen(this.maybeAttemptToConnectTimer_, goog.Timer.TICK,
<a name="line172"></a>          this.maybeAttemptToConnect_);
<a name="line173"></a>
<a name="line174"></a>  goog.log.info(goog.net.xpc.logger, &#39;NativeMessagingTransport created.  &#39; +
<a name="line175"></a>      &#39;protocolVersion=&#39; + this.protocolVersion_ + &#39;, oneSidedHandshake=&#39; +
<a name="line176"></a>      this.oneSidedHandshake_ + &#39;, role=&#39; + this.channel_.getRole());
<a name="line177"></a>};
<a name="line178"></a>goog.inherits(goog.net.xpc.NativeMessagingTransport, goog.net.xpc.Transport);
<a name="line179"></a>
<a name="line180"></a>
<a name="line181"></a>/**
<a name="line182"></a> * Length of the delay in milliseconds between the channel being connected and
<a name="line183"></a> * the connection callback being called, in cases where coverage of timing flaws
<a name="line184"></a> * is required.
<a name="line185"></a> * @type {number}
<a name="line186"></a> * @private
<a name="line187"></a> */
<a name="line188"></a>goog.net.xpc.NativeMessagingTransport.CONNECTION_DELAY_MS_ = 200;
<a name="line189"></a>
<a name="line190"></a>
<a name="line191"></a>/**
<a name="line192"></a> * Current determination of peer&#39;s protocol version, or null for unknown.
<a name="line193"></a> * @type {?number}
<a name="line194"></a> * @private
<a name="line195"></a> */
<a name="line196"></a>goog.net.xpc.NativeMessagingTransport.prototype.peerProtocolVersion_ = null;
<a name="line197"></a>
<a name="line198"></a>
<a name="line199"></a>/**
<a name="line200"></a> * Flag indicating if this instance of the transport has been initialized.
<a name="line201"></a> * @type {boolean}
<a name="line202"></a> * @private
<a name="line203"></a> */
<a name="line204"></a>goog.net.xpc.NativeMessagingTransport.prototype.initialized_ = false;
<a name="line205"></a>
<a name="line206"></a>
<a name="line207"></a>/**
<a name="line208"></a> * The transport type.
<a name="line209"></a> * @type {number}
<a name="line210"></a> * @override
<a name="line211"></a> */
<a name="line212"></a>goog.net.xpc.NativeMessagingTransport.prototype.transportType =
<a name="line213"></a>    goog.net.xpc.TransportTypes.NATIVE_MESSAGING;
<a name="line214"></a>
<a name="line215"></a>
<a name="line216"></a>/**
<a name="line217"></a> * The delimiter used for transport service messages.
<a name="line218"></a> * @type {string}
<a name="line219"></a> * @private
<a name="line220"></a> */
<a name="line221"></a>goog.net.xpc.NativeMessagingTransport.MESSAGE_DELIMITER_ = &#39;,&#39;;
<a name="line222"></a>
<a name="line223"></a>
<a name="line224"></a>/**
<a name="line225"></a> * Tracks the number of NativeMessagingTransport channels that have been
<a name="line226"></a> * initialized but not disposed yet in a map keyed by the UID of the window
<a name="line227"></a> * object.  This allows for multiple windows to be initiallized and listening
<a name="line228"></a> * for messages.
<a name="line229"></a> * @type {Object.&lt;number&gt;}
<a name="line230"></a> * @private
<a name="line231"></a> */
<a name="line232"></a>goog.net.xpc.NativeMessagingTransport.activeCount_ = {};
<a name="line233"></a>
<a name="line234"></a>
<a name="line235"></a>/**
<a name="line236"></a> * Id of a timer user during postMessage sends.
<a name="line237"></a> * @type {number}
<a name="line238"></a> * @private
<a name="line239"></a> */
<a name="line240"></a>goog.net.xpc.NativeMessagingTransport.sendTimerId_ = 0;
<a name="line241"></a>
<a name="line242"></a>
<a name="line243"></a>/**
<a name="line244"></a> * Checks whether the peer transport protocol version could be as indicated.
<a name="line245"></a> * @param {number} version The version to check for.
<a name="line246"></a> * @return {boolean} Whether the peer transport protocol version is as
<a name="line247"></a> *     indicated, or null.
<a name="line248"></a> * @private
<a name="line249"></a> */
<a name="line250"></a>goog.net.xpc.NativeMessagingTransport.prototype.couldPeerVersionBe_ =
<a name="line251"></a>    function(version) {
<a name="line252"></a>  return this.peerProtocolVersion_ == null ||
<a name="line253"></a>      this.peerProtocolVersion_ == version;
<a name="line254"></a>};
<a name="line255"></a>
<a name="line256"></a>
<a name="line257"></a>/**
<a name="line258"></a> * Initializes this transport. Registers a listener for &#39;message&#39;-events
<a name="line259"></a> * on the document.
<a name="line260"></a> * @param {Window} listenWindow The window to listen to events on.
<a name="line261"></a> * @private
<a name="line262"></a> */
<a name="line263"></a>goog.net.xpc.NativeMessagingTransport.initialize_ = function(listenWindow) {
<a name="line264"></a>  var uid = goog.getUid(listenWindow);
<a name="line265"></a>  var value = goog.net.xpc.NativeMessagingTransport.activeCount_[uid];
<a name="line266"></a>  if (!goog.isNumber(value)) {
<a name="line267"></a>    value = 0;
<a name="line268"></a>  }
<a name="line269"></a>  if (value == 0) {
<a name="line270"></a>    // Listen for message-events. These are fired on window in FF3 and on
<a name="line271"></a>    // document in Opera.
<a name="line272"></a>    goog.events.listen(
<a name="line273"></a>        listenWindow.postMessage ? listenWindow : listenWindow.document,
<a name="line274"></a>        &#39;message&#39;,
<a name="line275"></a>        goog.net.xpc.NativeMessagingTransport.messageReceived_,
<a name="line276"></a>        false,
<a name="line277"></a>        goog.net.xpc.NativeMessagingTransport);
<a name="line278"></a>  }
<a name="line279"></a>  goog.net.xpc.NativeMessagingTransport.activeCount_[uid] = value + 1;
<a name="line280"></a>};
<a name="line281"></a>
<a name="line282"></a>
<a name="line283"></a>/**
<a name="line284"></a> * Processes an incoming message-event.
<a name="line285"></a> * @param {goog.events.BrowserEvent} msgEvt The message event.
<a name="line286"></a> * @return {boolean} True if message was successfully delivered to a channel.
<a name="line287"></a> * @private
<a name="line288"></a> */
<a name="line289"></a>goog.net.xpc.NativeMessagingTransport.messageReceived_ = function(msgEvt) {
<a name="line290"></a>  var data = msgEvt.getBrowserEvent().data;
<a name="line291"></a>
<a name="line292"></a>  if (!goog.isString(data)) {
<a name="line293"></a>    return false;
<a name="line294"></a>  }
<a name="line295"></a>
<a name="line296"></a>  var headDelim = data.indexOf(&#39;|&#39;);
<a name="line297"></a>  var serviceDelim = data.indexOf(&#39;:&#39;);
<a name="line298"></a>
<a name="line299"></a>  // make sure we got something reasonable
<a name="line300"></a>  if (headDelim == -1 || serviceDelim == -1) {
<a name="line301"></a>    return false;
<a name="line302"></a>  }
<a name="line303"></a>
<a name="line304"></a>  var channelName = data.substring(0, headDelim);
<a name="line305"></a>  var service = data.substring(headDelim + 1, serviceDelim);
<a name="line306"></a>  var payload = data.substring(serviceDelim + 1);
<a name="line307"></a>
<a name="line308"></a>  goog.log.fine(goog.net.xpc.logger,
<a name="line309"></a>      &#39;messageReceived: channel=&#39; + channelName +
<a name="line310"></a>      &#39;, service=&#39; + service + &#39;, payload=&#39; + payload);
<a name="line311"></a>
<a name="line312"></a>  // Attempt to deliver message to the channel. Keep in mind that it may not
<a name="line313"></a>  // exist for several reasons, including but not limited to:
<a name="line314"></a>  //  - a malformed message
<a name="line315"></a>  //  - the channel simply has not been created
<a name="line316"></a>  //  - channel was created in a different namespace
<a name="line317"></a>  //  - message was sent to the wrong window
<a name="line318"></a>  //  - channel has become stale (e.g. caching iframes and back clicks)
<a name="line319"></a>  var channel = goog.net.xpc.channels[channelName];
<a name="line320"></a>  if (channel) {
<a name="line321"></a>    channel.xpcDeliver(service, payload, msgEvt.getBrowserEvent().origin);
<a name="line322"></a>    return true;
<a name="line323"></a>  }
<a name="line324"></a>
<a name="line325"></a>  var transportMessageType =
<a name="line326"></a>      goog.net.xpc.NativeMessagingTransport.parseTransportPayload_(payload)[0];
<a name="line327"></a>
<a name="line328"></a>  // Check if there are any stale channel names that can be updated.
<a name="line329"></a>  for (var staleChannelName in goog.net.xpc.channels) {
<a name="line330"></a>    var staleChannel = goog.net.xpc.channels[staleChannelName];
<a name="line331"></a>    if (staleChannel.getRole() == goog.net.xpc.CrossPageChannelRole.INNER &amp;&amp;
<a name="line332"></a>        !staleChannel.isConnected() &amp;&amp;
<a name="line333"></a>        service == goog.net.xpc.TRANSPORT_SERVICE_ &amp;&amp;
<a name="line334"></a>        (transportMessageType == goog.net.xpc.SETUP ||
<a name="line335"></a>        transportMessageType == goog.net.xpc.SETUP_NTPV2)) {
<a name="line336"></a>      // Inner peer received SETUP message but channel names did not match.
<a name="line337"></a>      // Start using the channel name sent from outer peer. The channel name
<a name="line338"></a>      // of the inner peer can easily become out of date, as iframe&#39;s and their
<a name="line339"></a>      // JS state get cached in many browsers upon page reload or history
<a name="line340"></a>      // navigation (particularly Firefox 1.5+). We can trust the outer peer,
<a name="line341"></a>      // since we only accept postMessage messages from the same hostname that
<a name="line342"></a>      // originally setup the channel.
<a name="line343"></a>      staleChannel.updateChannelNameAndCatalog(channelName);
<a name="line344"></a>      staleChannel.xpcDeliver(service, payload);
<a name="line345"></a>      return true;
<a name="line346"></a>    }
<a name="line347"></a>  }
<a name="line348"></a>
<a name="line349"></a>  // Failed to find a channel to deliver this message to, so simply ignore it.
<a name="line350"></a>  goog.log.info(goog.net.xpc.logger, &#39;channel name mismatch; message ignored&quot;&#39;);
<a name="line351"></a>  return false;
<a name="line352"></a>};
<a name="line353"></a>
<a name="line354"></a>
<a name="line355"></a>/**
<a name="line356"></a> * Handles transport service messages.
<a name="line357"></a> * @param {string} payload The message content.
<a name="line358"></a> * @override
<a name="line359"></a> */
<a name="line360"></a>goog.net.xpc.NativeMessagingTransport.prototype.transportServiceHandler =
<a name="line361"></a>    function(payload) {
<a name="line362"></a>  var transportParts =
<a name="line363"></a>      goog.net.xpc.NativeMessagingTransport.parseTransportPayload_(payload);
<a name="line364"></a>  var transportMessageType = transportParts[0];
<a name="line365"></a>  var peerEndpointId = transportParts[1];
<a name="line366"></a>  switch (transportMessageType) {
<a name="line367"></a>    case goog.net.xpc.SETUP_ACK_:
<a name="line368"></a>      this.setPeerProtocolVersion_(1);
<a name="line369"></a>      if (!this.setupAckReceived_.hasFired()) {
<a name="line370"></a>        this.setupAckReceived_.callback(true);
<a name="line371"></a>      }
<a name="line372"></a>      break;
<a name="line373"></a>    case goog.net.xpc.SETUP_ACK_NTPV2:
<a name="line374"></a>      if (this.protocolVersion_ == 2) {
<a name="line375"></a>        this.setPeerProtocolVersion_(2);
<a name="line376"></a>        if (!this.setupAckReceived_.hasFired()) {
<a name="line377"></a>          this.setupAckReceived_.callback(true);
<a name="line378"></a>        }
<a name="line379"></a>      }
<a name="line380"></a>      break;
<a name="line381"></a>    case goog.net.xpc.SETUP:
<a name="line382"></a>      this.setPeerProtocolVersion_(1);
<a name="line383"></a>      this.sendSetupAckMessage_(1);
<a name="line384"></a>      break;
<a name="line385"></a>    case goog.net.xpc.SETUP_NTPV2:
<a name="line386"></a>      if (this.protocolVersion_ == 2) {
<a name="line387"></a>        var prevPeerProtocolVersion = this.peerProtocolVersion_;
<a name="line388"></a>        this.setPeerProtocolVersion_(2);
<a name="line389"></a>        this.sendSetupAckMessage_(2);
<a name="line390"></a>        if ((prevPeerProtocolVersion == 1 || this.peerEndpointId_ != null) &amp;&amp;
<a name="line391"></a>            this.peerEndpointId_ != peerEndpointId) {
<a name="line392"></a>          // Send a new SETUP message since the peer has been replaced.
<a name="line393"></a>          goog.log.info(goog.net.xpc.logger,
<a name="line394"></a>              &#39;Sending SETUP and changing peer ID to: &#39; + peerEndpointId);
<a name="line395"></a>          this.sendSetupMessage_();
<a name="line396"></a>        }
<a name="line397"></a>        this.peerEndpointId_ = peerEndpointId;
<a name="line398"></a>      }
<a name="line399"></a>      break;
<a name="line400"></a>  }
<a name="line401"></a>};
<a name="line402"></a>
<a name="line403"></a>
<a name="line404"></a>/**
<a name="line405"></a> * Sends a SETUP transport service message of the correct protocol number for
<a name="line406"></a> * our current situation.
<a name="line407"></a> * @private
<a name="line408"></a> */
<a name="line409"></a>goog.net.xpc.NativeMessagingTransport.prototype.sendSetupMessage_ =
<a name="line410"></a>    function() {
<a name="line411"></a>  // &#39;real&#39; (legacy) v1 transports don&#39;t know about there being v2 ones out
<a name="line412"></a>  // there, and we shouldn&#39;t either.
<a name="line413"></a>  goog.asserts.assert(!(this.protocolVersion_ == 1 &amp;&amp;
<a name="line414"></a>      this.peerProtocolVersion_ == 2));
<a name="line415"></a>
<a name="line416"></a>  if (this.protocolVersion_ == 2 &amp;&amp; this.couldPeerVersionBe_(2)) {
<a name="line417"></a>    var payload = goog.net.xpc.SETUP_NTPV2;
<a name="line418"></a>    payload += goog.net.xpc.NativeMessagingTransport.MESSAGE_DELIMITER_;
<a name="line419"></a>    payload += this.endpointId_;
<a name="line420"></a>    this.send(goog.net.xpc.TRANSPORT_SERVICE_, payload);
<a name="line421"></a>  }
<a name="line422"></a>
<a name="line423"></a>  // For backward compatibility reasons, the V1 SETUP message can be sent by
<a name="line424"></a>  // both V1 and V2 transports.  Once a V2 transport has &#39;heard&#39; another V2
<a name="line425"></a>  // transport it starts ignoring V1 messages, so the V2 message must be sent
<a name="line426"></a>  // first.
<a name="line427"></a>  if (this.couldPeerVersionBe_(1)) {
<a name="line428"></a>    this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP);
<a name="line429"></a>  }
<a name="line430"></a>};
<a name="line431"></a>
<a name="line432"></a>
<a name="line433"></a>/**
<a name="line434"></a> * Sends a SETUP_ACK transport service message of the correct protocol number
<a name="line435"></a> * for our current situation.
<a name="line436"></a> * @param {number} protocolVersion The protocol version of the SETUP message
<a name="line437"></a> *     which gave rise to this ack message.
<a name="line438"></a> * @private
<a name="line439"></a> */
<a name="line440"></a>goog.net.xpc.NativeMessagingTransport.prototype.sendSetupAckMessage_ =
<a name="line441"></a>    function(protocolVersion) {
<a name="line442"></a>  goog.asserts.assert(this.protocolVersion_ != 1 || protocolVersion != 2,
<a name="line443"></a>      &#39;Shouldn\&#39;t try to send a v2 setup ack in v1 mode.&#39;);
<a name="line444"></a>  if (this.protocolVersion_ == 2 &amp;&amp; this.couldPeerVersionBe_(2) &amp;&amp;
<a name="line445"></a>      protocolVersion == 2) {
<a name="line446"></a>    this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP_ACK_NTPV2);
<a name="line447"></a>  } else if (this.couldPeerVersionBe_(1) &amp;&amp; protocolVersion == 1) {
<a name="line448"></a>    this.send(goog.net.xpc.TRANSPORT_SERVICE_, goog.net.xpc.SETUP_ACK_);
<a name="line449"></a>  } else {
<a name="line450"></a>    return;
<a name="line451"></a>  }
<a name="line452"></a>
<a name="line453"></a>  if (!this.setupAckSent_.hasFired()) {
<a name="line454"></a>    this.setupAckSent_.callback(true);
<a name="line455"></a>  }
<a name="line456"></a>};
<a name="line457"></a>
<a name="line458"></a>
<a name="line459"></a>/**
<a name="line460"></a> * Attempts to set the peer protocol number.  Downgrades from 2 to 1 are not
<a name="line461"></a> * permitted.
<a name="line462"></a> * @param {number} version The new protocol number.
<a name="line463"></a> * @private
<a name="line464"></a> */
<a name="line465"></a>goog.net.xpc.NativeMessagingTransport.prototype.setPeerProtocolVersion_ =
<a name="line466"></a>    function(version) {
<a name="line467"></a>  if (version &gt; this.peerProtocolVersion_) {
<a name="line468"></a>    this.peerProtocolVersion_ = version;
<a name="line469"></a>  }
<a name="line470"></a>  if (this.peerProtocolVersion_ == 1) {
<a name="line471"></a>    if (!this.setupAckSent_.hasFired() &amp;&amp; !this.oneSidedHandshake_) {
<a name="line472"></a>      this.setupAckSent_.callback(true);
<a name="line473"></a>    }
<a name="line474"></a>    this.peerEndpointId_ = null;
<a name="line475"></a>  }
<a name="line476"></a>};
<a name="line477"></a>
<a name="line478"></a>
<a name="line479"></a>/**
<a name="line480"></a> * Connects this transport.
<a name="line481"></a> * @override
<a name="line482"></a> */
<a name="line483"></a>goog.net.xpc.NativeMessagingTransport.prototype.connect = function() {
<a name="line484"></a>  goog.net.xpc.NativeMessagingTransport.initialize_(this.getWindow());
<a name="line485"></a>  this.initialized_ = true;
<a name="line486"></a>  this.maybeAttemptToConnect_();
<a name="line487"></a>};
<a name="line488"></a>
<a name="line489"></a>
<a name="line490"></a>/**
<a name="line491"></a> * Connects to other peer. In the case of the outer peer, the setup messages are
<a name="line492"></a> * likely sent before the inner peer is ready to receive them. Therefore, this
<a name="line493"></a> * function will continue trying to send the SETUP message until the inner peer
<a name="line494"></a> * responds. In the case of the inner peer, it will occasionally have its
<a name="line495"></a> * channel name fall out of sync with the outer peer, particularly during
<a name="line496"></a> * soft-reloads and history navigations.
<a name="line497"></a> * @private
<a name="line498"></a> */
<a name="line499"></a>goog.net.xpc.NativeMessagingTransport.prototype.maybeAttemptToConnect_ =
<a name="line500"></a>    function() {
<a name="line501"></a>  // In a one-sided handshake, the outer frame does not send a SETUP message,
<a name="line502"></a>  // but the inner frame does.
<a name="line503"></a>  var outerFrame = this.channel_.getRole() ==
<a name="line504"></a>      goog.net.xpc.CrossPageChannelRole.OUTER;
<a name="line505"></a>  if ((this.oneSidedHandshake_ &amp;&amp; outerFrame) ||
<a name="line506"></a>      this.channel_.isConnected() ||
<a name="line507"></a>      this.isDisposed()) {
<a name="line508"></a>    this.maybeAttemptToConnectTimer_.stop();
<a name="line509"></a>    return;
<a name="line510"></a>  }
<a name="line511"></a>  this.maybeAttemptToConnectTimer_.start();
<a name="line512"></a>  this.sendSetupMessage_();
<a name="line513"></a>};
<a name="line514"></a>
<a name="line515"></a>
<a name="line516"></a>/**
<a name="line517"></a> * Sends a message.
<a name="line518"></a> * @param {string} service The name off the service the message is to be
<a name="line519"></a> * delivered to.
<a name="line520"></a> * @param {string} payload The message content.
<a name="line521"></a> * @override
<a name="line522"></a> */
<a name="line523"></a>goog.net.xpc.NativeMessagingTransport.prototype.send = function(service,
<a name="line524"></a>                                                                payload) {
<a name="line525"></a>  var win = this.channel_.getPeerWindowObject();
<a name="line526"></a>  if (!win) {
<a name="line527"></a>    goog.log.fine(goog.net.xpc.logger, &#39;send(): window not ready&#39;);
<a name="line528"></a>    return;
<a name="line529"></a>  }
<a name="line530"></a>
<a name="line531"></a>  this.send = function(service, payload) {
<a name="line532"></a>    // In IE8 (and perhaps elsewhere), it seems like postMessage is sometimes
<a name="line533"></a>    // implemented as a synchronous call.  That is, calling it synchronously
<a name="line534"></a>    // calls whatever listeners it has, and control is not returned to the
<a name="line535"></a>    // calling thread until those listeners are run.  This produces different
<a name="line536"></a>    // ordering to all other browsers, and breaks this protocol.  This timer
<a name="line537"></a>    // callback is introduced to produce standard behavior across all browsers.
<a name="line538"></a>    var transport = this;
<a name="line539"></a>    var channelName = this.channel_.name;
<a name="line540"></a>    var sendFunctor = function() {
<a name="line541"></a>      transport.sendTimerId_ = 0;
<a name="line542"></a>
<a name="line543"></a>      try {
<a name="line544"></a>        // postMessage is a method of the window object, except in some
<a name="line545"></a>        // versions of Opera, where it is a method of the document object.  It
<a name="line546"></a>        // also seems that the appearance of postMessage on the peer window
<a name="line547"></a>        // object can sometimes be delayed.
<a name="line548"></a>        var obj = win.postMessage ? win : win.document;
<a name="line549"></a>        if (!obj.postMessage) {
<a name="line550"></a>          goog.log.warning(goog.net.xpc.logger,
<a name="line551"></a>              &#39;Peer window had no postMessage function.&#39;);
<a name="line552"></a>          return;
<a name="line553"></a>        }
<a name="line554"></a>
<a name="line555"></a>        obj.postMessage(channelName + &#39;|&#39; + service + &#39;:&#39; + payload,
<a name="line556"></a>            transport.peerHostname_);
<a name="line557"></a>        goog.log.fine(goog.net.xpc.logger, &#39;send(): service=&#39; + service +
<a name="line558"></a>            &#39; payload=&#39; + payload + &#39; to hostname=&#39; + transport.peerHostname_);
<a name="line559"></a>      } catch (error) {
<a name="line560"></a>        // There is some evidence (not totally convincing) that postMessage can
<a name="line561"></a>        // be missing or throw errors during a narrow timing window during
<a name="line562"></a>        // startup.  This protects against that.
<a name="line563"></a>        goog.log.warning(goog.net.xpc.logger,
<a name="line564"></a>            &#39;Error performing postMessage, ignoring.&#39;, error);
<a name="line565"></a>      }
<a name="line566"></a>    };
<a name="line567"></a>    this.sendTimerId_ = goog.Timer.callOnce(sendFunctor, 0);
<a name="line568"></a>  };
<a name="line569"></a>  this.send(service, payload);
<a name="line570"></a>};
<a name="line571"></a>
<a name="line572"></a>
<a name="line573"></a>/**
<a name="line574"></a> * Notify the channel that this transport is connected.  If either transport is
<a name="line575"></a> * protocol v1, a short delay is required to paper over timing vulnerabilities
<a name="line576"></a> * in that protocol version.
<a name="line577"></a> * @private
<a name="line578"></a> */
<a name="line579"></a>goog.net.xpc.NativeMessagingTransport.prototype.notifyConnected_ =
<a name="line580"></a>    function() {
<a name="line581"></a>  var delay = (this.protocolVersion_ == 1 || this.peerProtocolVersion_ == 1) ?
<a name="line582"></a>      goog.net.xpc.NativeMessagingTransport.CONNECTION_DELAY_MS_ : undefined;
<a name="line583"></a>  this.channel_.notifyConnected(delay);
<a name="line584"></a>};
<a name="line585"></a>
<a name="line586"></a>
<a name="line587"></a>/** @override */
<a name="line588"></a>goog.net.xpc.NativeMessagingTransport.prototype.disposeInternal = function() {
<a name="line589"></a>  if (this.initialized_) {
<a name="line590"></a>    var listenWindow = this.getWindow();
<a name="line591"></a>    var uid = goog.getUid(listenWindow);
<a name="line592"></a>    var value = goog.net.xpc.NativeMessagingTransport.activeCount_[uid];
<a name="line593"></a>    goog.net.xpc.NativeMessagingTransport.activeCount_[uid] = value - 1;
<a name="line594"></a>    if (value == 1) {
<a name="line595"></a>      goog.events.unlisten(
<a name="line596"></a>          listenWindow.postMessage ? listenWindow : listenWindow.document,
<a name="line597"></a>          &#39;message&#39;,
<a name="line598"></a>          goog.net.xpc.NativeMessagingTransport.messageReceived_,
<a name="line599"></a>          false,
<a name="line600"></a>          goog.net.xpc.NativeMessagingTransport);
<a name="line601"></a>    }
<a name="line602"></a>  }
<a name="line603"></a>
<a name="line604"></a>  if (this.sendTimerId_) {
<a name="line605"></a>    goog.Timer.clear(this.sendTimerId_);
<a name="line606"></a>    this.sendTimerId_ = 0;
<a name="line607"></a>  }
<a name="line608"></a>
<a name="line609"></a>  goog.dispose(this.eventHandler_);
<a name="line610"></a>  delete this.eventHandler_;
<a name="line611"></a>
<a name="line612"></a>  goog.dispose(this.maybeAttemptToConnectTimer_);
<a name="line613"></a>  delete this.maybeAttemptToConnectTimer_;
<a name="line614"></a>
<a name="line615"></a>  this.setupAckReceived_.cancel();
<a name="line616"></a>  delete this.setupAckReceived_;
<a name="line617"></a>  this.setupAckSent_.cancel();
<a name="line618"></a>  delete this.setupAckSent_;
<a name="line619"></a>  this.connected_.cancel();
<a name="line620"></a>  delete this.connected_;
<a name="line621"></a>
<a name="line622"></a>  // Cleaning up this.send as it is an instance method, created in
<a name="line623"></a>  // goog.net.xpc.NativeMessagingTransport.prototype.send and has a closure over
<a name="line624"></a>  // this.channel_.peerWindowObject_.
<a name="line625"></a>  delete this.send;
<a name="line626"></a>
<a name="line627"></a>  goog.net.xpc.NativeMessagingTransport.base(this, &#39;disposeInternal&#39;);
<a name="line628"></a>};
<a name="line629"></a>
<a name="line630"></a>
<a name="line631"></a>/**
<a name="line632"></a> * Parse a transport service payload message.  For v1, it is simply expected to
<a name="line633"></a> * be &#39;SETUP&#39; or &#39;SETUP_ACK&#39;.  For v2, an example setup message is
<a name="line634"></a> * &#39;SETUP_NTPV2,abc123&#39;, where the second part is the endpoint id.  The v2 setup
<a name="line635"></a> * ack message is simply &#39;SETUP_ACK_NTPV2&#39;.
<a name="line636"></a> * @param {string} payload The payload.
<a name="line637"></a> * @return {!Array.&lt;?string&gt;} An array with the message type as the first member
<a name="line638"></a> *     and the endpoint id as the second, if one was sent, or null otherwise.
<a name="line639"></a> * @private
<a name="line640"></a> */
<a name="line641"></a>goog.net.xpc.NativeMessagingTransport.parseTransportPayload_ =
<a name="line642"></a>    function(payload) {
<a name="line643"></a>  var transportParts = /** @type {!Array.&lt;?string&gt;} */ (payload.split(
<a name="line644"></a>      goog.net.xpc.NativeMessagingTransport.MESSAGE_DELIMITER_));
<a name="line645"></a>  transportParts[1] = transportParts[1] || null;
<a name="line646"></a>  return transportParts;
<a name="line647"></a>};
</pre>


</body>
</html>
